import React from 'react';
import { Card, Button, Form, Row, Col, Input, Divider, Modal, message } from 'antd';
import moment from 'moment';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import SimpleTable from '@/components/SimpleTable';

import $api from '@/api';
import AdminActionModal from './AdminActionModal';
import styles from './style.less';

const FormItem = Form.Item;

const titleMap = { Add: '添加', Edit: '编辑', Freeze: '冻结', ResetPassword: '重置密码' };

@Form.create()
export default class AdminList extends React.PureComponent {
  state = {
    loading: false,
    data: {
      list: [],
      total: 0,
      pageNo: 1,
      pageSize: 10,
    },
    record: undefined,
    modalAction: '',
    visible: false,
    roleList: [],
    submitting: false,
  };

  columns = [
    { title: 'ID', dataIndex: 'id' },
    { title: '昵称', dataIndex: 'nickname' },
    { title: '用户名', dataIndex: 'username' },
    { title: '角色', dataIndex: 'roleName' },
    { title: '最后登录时间', dataIndex: 'loginTime', render: val => (val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : '') },
    {
      title: '操作',
      dataIndex: '_op',
      render: (val, record) => (
          <>
            <a onClick={() => this.handleModalVisible(true, record, 'Edit')}>修改</a>
            <Divider type="vertical" /><a onClick={() => this.handleModalVisible(true, record, 'ResetPassword')}>重置密码</a>
            {!record.isFreeze && <><Divider type="vertical" /><a style={{ color: '#F00' }} onClick={() => this.handleModalVisible(true, record, 'Freeze')}>冻结</a> </>}
            {record.isFreeze && <><Divider type="vertical" /><a onClick={() => this.handleUnFreeze(record)}>解冻</a> </>}
          </>
        ),
    },
  ];

  componentDidMount() {
    this.handleSearch();
  }

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
  };

  handleSearch = (params = {}) => {
    const { data: { pageNo, pageSize } } = this.state;
    const { form } = this.props;
    this.setState({ loading: true });
    form.validateFields((errors, values) => {
      if (errors) {
        return;
      }
      $api.admin.findPage({ pageNo, pageSize, ...values, ...params })
        .then(resp => {
          if (resp.code === 0) {
            this.state.data = resp.data;
          }
          this.setState({ loading: false })
        })
    });
  };


  handleModalVisible = (visible, record, action) => {
    if (visible) {
      if (action === 'Add' || action === 'Edit') {
        $api.role.findList()
            .then(resp => {
              if (resp.code === 0) {
                this.setState({ roleList: resp.data })
              }
            })
      }
      this.setState({ visible, record, modalAction: action })
    } else {
      this.setState({ visible, record: false, modalAction: '' })
    }
  };

  // 解冻
  handleUnFreeze = record => {
    Modal.confirm({
      title: '确认解冻管理员？',
      onOk: () => {
        $api.admin.unFreeze(record.id)
          .then(resp => {
            if (resp.code === 0) {
              message.success(resp.message);
              this.handleSearch();
            }
          })
      },
    })
  };

  // 冻结
  handleFreeze = values => {
    const { record } = this.state;
    this.setState({ submitting: true });
    $api.admin.freeze(record.id, values)
      .then(resp => {
        if (resp.code === 0) {
          message.success(resp.message);
          this.handleModalVisible(false);
          this.handleSearch();
        }
      })
      .finally(() => this.setState({ submitting: false }))
  };

  // 重置密码
  handleResetPassword = values => {
    const { record } = this.state;
    this.setState({ submitting: true });
    $api.admin.resetPassword(record.id, values)
      .then(resp => {
        if (resp.code === 0) {
          message.success(resp.message);
          this.handleModalVisible(false);
          this.handleSearch();
        }
      })
      .finally(() => this.setState({ submitting: false }))
  };

  handleAdd = values => {
    this.setState({ submitting: true });
    $api.admin.add(values)
      .then(resp => {
        if (resp.code === 0) {
          message.success('保存成功');
          this.handleModalVisible(false);
          this.handleSearch()
        }
      })
      .finally(() => this.setState({ submitting: false }))
  };

  handleEdit = values => {
    const { record } = this.state;
    this.setState({ submitting: true });
    $api.admin.edit(record.id, values)
      .then(resp => {
        if (resp.code === 0) {
          message.success('保存成功');
          this.handleModalVisible(false);
          this.handleSearch()
        }
      })
      .finally(() => this.setState({ submitting: false }))
  };

  renderForm() {
    const { form: { getFieldDecorator } } = this.props;
    return (
      <Form>
        <Row gutter={16}>
          <Col span={8}>
            <FormItem label="用户名">
              {getFieldDecorator('no')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="昵称">
              {getFieldDecorator('nickname')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col span={8}>
            <span className={styles.submitButtons}>
              <Button type="primary" onClick={() => this.handleSearch({ pageNo: 1 })}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    )
  }

  render() {
    const { data, loading, modalAction, visible, record, roleList, submitting } = this.state;

    const actionProps = {
      visible,
      modalAction,
      roleList,
      confirmLoading: submitting,
      data: record,
      title: titleMap[modalAction],
      onOk: this[`handle${modalAction}`],
      onCancel: () => this.handleModalVisible(false),
    };

    return (
      <>
        <PageHeaderWrapper breadcrumb={false} title="管理员列表">
          <Card bordered={false}>
            <div className={styles.tableList}>
              <div className={styles.tableListForm}>{this.renderForm()}</div>
              <div className={styles.tableListOperator}>
                <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true, undefined, 'Add')}>
                  新建
                </Button>
              </div>
              <SimpleTable
                loading={loading}
                columns={this.columns}
                data={data}
                onChange={this.handleSearch}
              />
            </div>
          </Card>
        </PageHeaderWrapper>
        <AdminActionModal {...actionProps} />
      </>
    );
  }
}
